package com.bondex.charter.commons;

import com.bondex.global.utils.HttpConnectUtil;
import com.bondex.viresult.dto.BondexMailDTO;
import com.bondex.viresult.dto.BondexMailPushDTO;
import com.bondex.viresult.dto.MailMsgResponse;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <pre>
 * 描述：邮件发送工具类
 * </pre>
 *
 * @author： wh
 * @date: 2021/9/15 17:51
 */
@Configuration
@Service
public class MailUtil {

    @Value("${charter.application_id}")
    private String applicationId;

    @Value("${charter.application_name}")
    private String applicationName;

    @Value("${charter.mail.pushurl}")
    private String mailPushUrl;

    protected Logger log = LoggerFactory.getLogger(MailUtil.class);

    public MailMsgResponse pushMail(BondexMailDTO bondexMailDTO) {
        Gson gson = new Gson();
        // 补全邮件其他信息
        BondexMailPushDTO bondexMailPushDTO = new BondexMailPushDTO();
        // 推送方式——邮件
        bondexMailPushDTO.setBusinessType(1);
        // 调用应用的appid
        bondexMailPushDTO.setAppId(applicationId);
        // 调用应用名称
        bondexMailPushDTO.setAppName(applicationName);
        // 邮件实体
        bondexMailPushDTO.setEmail(bondexMailDTO);
        // 邮件实体转json
        String request = gson.toJson(bondexMailPushDTO);
        Map<String, String> headers = new HashMap<>(2);
        headers.put("Content-Type", "application/json");
        // 返回邮件请求结果
        log.info("邮件发送JSON：{}。", request);
        //日志上传

        //推送给邮件系统
        String response = HttpConnectUtil.doHttpPostHasHeader(mailPushUrl, request, headers);
        MailMsgResponse commonMsgResponse = gson.fromJson(response,MailMsgResponse.class);
        if (commonMsgResponse.getSuccess()) {
            log.info("邮件发送成功",response);
        }else {
            log.info("邮件发送失败",response);
        }
        return commonMsgResponse;
    }
}
